import { ref } from "vue";
import Sort from "@/models/Sort";

// 表格排序.
export default function TableSortEvent(
  props: {
    tableData: Array<Record<string, unknown>>;
  },
  emit: { (e: "sort-change", data: Array<Record<string, unknown>>): void }
) {
  // 默认排序.
  const defaultSort = ref({ prop: "id", order: "descending" });

  // 当前排序的字段.
  const sortKey = ref("id");

  // 修改排序.
  const sortChange = (sort: Sort) => {
    sortKey.value = sort.prop;
    // 排序时可能会有空值, 将空值考虑在内.
    // 当前拍序字段的值非空的数据.
    const notNullData = [];
    // 当前拍序字段的值为空的数据.
    const nullData = [];
    for (let i = 0; i < props.tableData.length; i++) {
      let temp = null;
      temp = props.tableData[i][sortKey.value];
      if (temp === null || undefined === temp) {
        nullData.push(props.tableData[i]);
      } else {
        notNullData.push(props.tableData[i]);
      }
    }
    switch (sort.order) {
      case null:
        break;
      case "ascending":
        notNullData.sort(sortAsc);
        break;
      case "descending":
        notNullData.sort(sortDesc);
        break;
    }
    // 排完序之后的数据, 当前排序字段为空的数据放在所有数据之后.
    const data = notNullData.concat(nullData);
    emit("sort-change", data);
  };

  // 正序排序.
  const sortAsc = (a: Record<string, unknown>, b: Record<string, unknown>) => {
    a[sortKey.value] = a[sortKey.value] === "" ? "" : a[sortKey.value];
    b[sortKey.value] = b[sortKey.value] === "" ? "" : b[sortKey.value];
    if (typeof b[sortKey.value] === "number") {
      const c = a as Record<string, number>;
      const d = b as Record<string, number>;
      return d[sortKey.value] - c[sortKey.value];
    } else {
      const c = a as Record<string, string>;
      const d = b as Record<string, string>;
      return d[sortKey.value].localeCompare(c[sortKey.value]);
    }
  };

  // 倒序排序.
  const sortDesc = (a: Record<string, unknown>, b: Record<string, unknown>) => {
    a[sortKey.value] = a[sortKey.value] === "" ? "" : a[sortKey.value];
    b[sortKey.value] = b[sortKey.value] === "" ? "" : b[sortKey.value];
    if (typeof b[sortKey.value] === "number") {
      const c = a as Record<string, number>;
      const d = b as Record<string, number>;
      return c[sortKey.value] - d[sortKey.value];
    } else {
      const c = a as Record<string, string>;
      const d = b as Record<string, string>;
      return c[sortKey.value].localeCompare(d[sortKey.value]);
    }
  };
  return { defaultSort, sortChange };
}
